import request from '@/utils/request'

export function download(url, fileName) {
  const config = {
    responseType: 'blob'
  }
  return new Promise((resolve, reject) => {
    request.get(`${url}/${fileName}`, config)
      .then((res) => {
        if (res && res.data && res.data.type !== 'application/json') {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName)
          } else {
            var link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            // 释放内存
            window.URL.revokeObjectURL(link.href)
          }
          resolve(res)
        } else {
          Message.error({ message: '下载文件失败' })
          reject(res)
        }
      })
      .catch((res) => {
        this.$message({
          type: 'error',
          message: '下载文件失败'
        })
      })
  })
}
